/**
 * 库存管理
 */
;$(function () {
    $("#stockCategory2").attr("disabled", "disabled");
    layui.use(['form', 'table'], function () {
        var form = layui.form,
            table = layui.table;
        table.render({
            elem: '#stockInfoTable'
            , url: 'getStock'
            , response: {
                statusCode: true
            }
            , where: {
                idOrName: $("#stockWaresIdVal").val(),//为""或者value
                category1: $('#stockCategory1').find('option:selected').attr('value'),
                category2: $('#stockCategory2').find('option:selected').attr('value'),
            }
            , method: "POST"
            , defaultToolbar: [] //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
            , cellMinWidth: 70 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[
                {field: 'sorts', title: '序号', event: "checkBoxChange", templet: '#sort', width: 58, align: 'center'}
                , {field: 'id', title: '条码', align: 'center'}
                , {field: 'name', title: '商品名称', align: 'center'}
                , {field: 'category', title: '分类', align: 'center', width: 180}
                , {field: 'unit', title: '库存单位', align: 'center'}
                , {
                    field: 'minInventory',
                    title: '最低库存',
                    align: 'center',
                    templet: function (d) {
                        if (d.minInventory !== null) {
                            return '<span style="text-decoration:underline;cursor:pointer;color: #338BFF" ' +
                                'lay-event="minInventorySet">' + d.minInventory + '</span>'
                        } else {
                            return '<span style="text-decoration:underline;cursor:pointer;color: #338BFF" ' +
                                'lay-event="minInventorySet">未设置</span>'
                        }
                    },
                }
                , {
                    field: 'inventory',
                    title: '当前库存',
                    align: 'center',
                    templet: function (d) {
                        return '<span style="text-decoration:underline;cursor:pointer;color: #338BFF" lay-event="inventorySet">' + d.inventory + '</span>'
                    },
                }
                , {
                    field: 'state', title: '状态', align: 'center',
                    templet: function (d) {
                        if (d.inventory < 0) {
                            return '<span style="color:#D92E2E;">库存异常</span>'
                        } else if (d.inventory >= 0 && d.minInventory !== null && d.inventory < d.minInventory) {
                            return '<span style="color:#FFBA15;">库存不足</span>'
                        } else if (d.inventory >= 0 && d.minInventory !== null && d.inventory >= d.minInventory) {
                            return '<span style="color:#13CE67;">库存充足</span>'
                        } else if (d.minInventory === null) {
                            return '<span ></span>'
                        }
                    }
                }
                , {
                    field: 'purchase', title: '进价(元)', align: 'center', templet: function (d) {
                        return d.purchase.toFixed(2);
                    }
                }
                , {
                    field: 'price', title: '售价(元)', align: 'center', templet: function (d) {
                        return d.price.toFixed(2);
                    }
                }
            ]]
            , page: true
            , id: 'reloadStockInfoTable'
        });
        table.on('tool(stockInfoTable)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'minInventorySet':
                    let firstTitle = "修改";
                    let minInventoryValue = data.minInventory;
                    if (minInventoryValue === "未设置") {
                        minInventoryValue = "";
                        firstTitle = "设置"
                    }
                    layer.prompt({
                        formType: 0
                        , title: firstTitle + '[' + data.name + ']的最低库存为：'
                        , value: minInventoryValue
                    }, function (value, index) {
                        if (value != null) {
                            $.post('updateMinInventoryValue', {
                                id: data.id,
                                minInventoryValue: value
                            }, function (result) {
                                if (result.code === true) {
                                    table.reload('reloadStockInfoTable', {
                                        page: {
                                            curr: 1 //重新从第 1 页开始
                                        }
                                    });
                                    // obj.update({
                                    //     minInventory: value
                                    // });
                                } else {
                                    layer.msg(result.msg);
                                }
                            });
                        }
                        layer.close(index);
                    });
                    //待修改
                    // $(".layui-layer-content").find('input').attr('style','padding-right: 60px;');
                    // $(".layui-layer-content").append('<span class="span" style="position: absolute;top: 0;right: 0px;">天</span>');
                    break;
                case 'inventorySet':
                    layer.prompt({
                        formType: 0
                        , title: '修改[' + data.name + ']的当前库存为：'
                        , value: data.inventory
                    }, function (value, index) {
                        if (value != null) {
                            $.post('updateInventoryValue', {
                                id: data.id,
                                inventoryValue: value
                            }, function (result) {
                                if (result.code === true) {
                                    table.reload('reloadStockInfoTable', {
                                        page: {
                                            curr: 1 //重新从第 1 页开始
                                        }
                                    });
                                    getStockReportEChartsOption();
                                } else {
                                    layer.msg(result.msg);
                                }
                            });
                        }
                        layer.close(index);
                    });
                    break;
            }
        });
        form.on('select(stockCategory1)', function (CategoryData) {
            let firstCategoryId = CategoryData.value;
            $("#stockCategory2").empty();
            $("#stockCategory2").append('<option value="">全部</option>');
            if (firstCategoryId != "") {
                $("#stockCategory2").removeAttr("disabled");
                $.ajax({
                    url: 'getCategory2',
                    type: "POST",
                    data: {
                        "firstCategoryId": firstCategoryId,
                    },
                    dataType: "json",
                    async: false,//改为true会添加不上分类二，大概是还没加上函数就结束了
                    success: function (result) {
                        if (result.code === true) {
                            for (var i = 0; i < result.category2.length; i++) {
                                $("#stockCategory2").append("<option value=" + result.category2[i].categoryId + ">" + result.category2[i].categoryName + "</option>")
                            }
                            form.render('select');

                        } else {
                            layer.msg(result.msg);
                        }
                    },
                    error: function () {
                        layer.msg("拉取失败，稍后再试");
                    }
                });
            } else {
                $("#stockCategory2").empty();
                $("#stockCategory2").attr("disabled", "disabled");
            }
            form.render('select');
            $("#waresIdOrNameBtn").click();
        });
        form.on('select(stockCategory2)', function (CategoryData) {
            $("#waresIdOrNameBtn").click();
        });
        $("#waresIdOrNameBtn").click(function () {
            let idOrName = $("#stockWaresIdVal").val(); //为""或者value
            let category1 = $('#stockCategory1').find('option:selected').attr('value');
            let category2 = $('#stockCategory2').find('option:selected').attr('value');
            table.reload('reloadStockInfoTable', {
                where: {
                    idOrName: idOrName,
                    category1: category1,
                    category2: category2,
                },
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });

        // 基于准备好的dom，初始化echarts实例inventoryCategoryProportion
        var myChart = echarts.init(document.getElementById('inventoryCategoryProportion'));

        getStockReportEChartsOption();
        getStockShowData();

        function getStockReportEChartsOption() {
            $.ajax({
                url: 'loadStockReport',
                type: "post",
                dataType: "json",
                // async: false,
                success: function (result) {
                    if (result.code === true) {
                        let option = {
                            tooltip: {
                                trigger: 'item',
                                formatter: '{a} <br/>{b}: {c} 元 '
                            },
                            legend: {
                                orient: 'vertical',
                                left: 10,
                            },
                            series: [
                                {
                                    name: '库存价值',
                                    type: 'pie',
                                    radius: ['45%', '70%'],
                                    avoidLabelOverlap: true,//防止重叠
                                    label: {
                                        normal: {
                                            formatter: '{b}:({d}%)',
                                            textStyle: {
                                                fontWeight: 'normal',
                                                fontSize: 15
                                            },
                                        },
                                        emphasis: {
                                            show: true,
                                            textStyle: {
                                                fontSize: '20',
                                                fontWeight: 'bold'
                                            }
                                        }
                                    },
                                    labelLine: {
                                        normal: {
                                            show: true
                                        }
                                    },
                                    data: result.data
                                }
                            ]
                        };
                        myChart.setOption(option);
                    } else {
                        layer.msg(result.msg);
                    }
                },
            });
        }

        function getStockShowData() {
            $.ajax({
                url: 'getStockShowData',
                type: "post",
                dataType: "json",
                async: false,
                success: function (result) {
                    if (result.code === true) {
                        $("#stockShowWaresTotals").html(result.waresTotals + '种');
                        $("#stockShowCastTotals").html('￥' + result.castTotals.toFixed(2));
                        $("#stockShowPriceTotals").html('￥' + result.priceTotals.toFixed(2));
                    } else {
                        layer.msg(result.msg);
                    }
                },
            });

        }


    });

});